package com.car.commons.web.sentinel;

import cn.hutool.json.JSONUtil;
import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.car.commons.core.model.Result;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class BlockHandler implements BlockExceptionHandler {
    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, BlockException e) throws Exception {
        Result<?> result = Result.getResult().setCode(4000).setMsg("被限制");
        if (e instanceof FlowException) {
            result.setMsg("限流");
        } else if (e instanceof DegradeException) {
            result.setMsg("熔断");
        }
        httpServletResponse.setContentType("application/json;charset=utf8");
        httpServletResponse.setCharacterEncoding("utf8");
        String s = JSONUtil.parse(result).toString();
        httpServletResponse.getWriter().write(s);
        httpServletResponse.getWriter().flush();
    }
}
